# -*- coding: utf-8 -*-
"""
@author: wyb
@date: 2024/1/12
@time: 20:33
@desc: 从雪球获取符合条件的股票列表
"""
import requests, json

'''
 基地址
'''
_baseurl = 'https://xueqiu.com/service/screener/screen?category=CN&exchange=sha&areacode='


def getstocklist(condition):
    '''
     调研雪球获取条件股票的接口，并解析返回值
    :param condition: 条件，要根据雪球网站的条件
    :return: 符合条件的股票列表，如果没有，则返回空列表
    '''
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
    }

    stocks = []
    url = _baseurl + condition
    response = requests.get(url, headers=headers)
    try:
        response.raise_for_status()
        # HTTP 请求成功，继续处理响应数据
        if response.status_code == 200:
            result = response.text
            data = json.loads(result)
            lis = data['data']['list']
            stocks = [{'symbol': obj['symbol'][2:], 'name': obj['name']} for obj in lis]
        else:
            print(f"Error: {response.status_code}")
        return stocks
    except requests.HTTPError as e:
        print(f"HTTP请求错误: {e}")
